using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections;
using System.Windows.Navigation;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using AiyoriAoshi.MangaService;
using System.Collections.ObjectModel;
using Microsoft.Phone.Net.NetworkInformation;
using DBDataContext.Model;

namespace AiyoriAoshi
{
    public partial class ChaptersPage : PhoneApplicationPage
    {

        IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;

        public ChaptersPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            App.ViewModel.GetChaptersByMangaId((int)iss["MangaId"]);
            ListChapter.DataContext = App.ViewModel;

            base.OnNavigatedTo(e);
        }

        private void btnGo_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ContentPage.xaml", UriKind.Relative));
        }

        private void btnGoToIntroPage_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/IntroPage.xaml", UriKind.Relative));
        }

        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            Button button = (Button)sender;
            int chapterId = int.Parse(button.Tag.ToString());

            Chapter currentChap = App.ViewModel.GetChapterByChapterId(chapterId);
            System.Windows.Controls.Image testImageSource = (System.Windows.Controls.Image)button.Content;
            //MessageBox.Show(testImageSource.);
            // it's downloading
            if (currentChap.Status == 2)
            {
                MessageBoxResult result = MessageBox.Show("Do you want to stop downloading?", "Confirm", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    ChapterDownload stopDownloadingChapter = new ChapterDownload(chapterId);
                    stopDownloadingChapter.Stop();
                }
            }
            // or not
            else
            {
                MessageBoxResult result = MessageBox.Show("Do you want to download data of this chapter?", "Confirm", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    var ni = NetworkInterface.NetworkInterfaceType;

                    //if (NetworkInterface.GetIsNetworkAvailable() == false)
                    if (ni == NetworkInterfaceType.None)
                    {
                        MessageBox.Show("You don't have any connection. Please try again.");
                        return;
                    }

                    try
                    {
                        MangaServiceClient service = new MangaServiceClient();
                        ChapterDownload chapterDownload = new ChapterDownload(chapterId);
                        chapterDownload.Start();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error when downloading chapter data. Message: " + ex.Message);
                    }
                }
            }
        }


        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Do you want to delete all data of this chapter?", "Confirm", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                try
                {
                    Button btnMove = (Button)sender;

                    int chapterId = int.Parse(btnMove.Tag.ToString());
                    Chapter chapter = App.ViewModel.GetChapterByChapterId(chapterId);
                    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string path = String.Format("Shared/Download/{0}/{1}/", chapter.MangaId, chapter.ChapterId);
                        string searchPattern = path + "*";

                        try
                        {
                            string[] listFileNames = isf.GetFileNames(searchPattern);
                            foreach (string fileName in listFileNames)
                                isf.DeleteFile(path + "/" + fileName);
                            App.ViewModel.UpdateIsDownloadedImageAndStatusChapterBaseOnChapterId(chapterId);

                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Gặp lỗi khi chuyển trang: " + ex.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Lỗi xảy ra khi chuyển trang: " + ex.Message);
                }
            }
        }

        private void btnMove_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btnMove = (Button)sender;

                int chapterId = int.Parse(btnMove.Tag.ToString());
                //Chapter chapter = App.ViewModel.GetChapterByChapterId(chapterId);

                string strUri = String.Format("/ContentPage.xaml?chapterId={0}", chapterId);
                NavigationService.Navigate(new Uri(strUri, UriKind.Relative));

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error when change page: " + ex.Message);
            }
        }

        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            // Check chapter list, if it has some chapter (mean: not the first time launch app / downloaded data)
            // Get new chapter list, 
            // count new list, count old list
            // different = newlist.count - oldlist.count
            // insert new chapter if different > 0
            UpdateChapterList();
        }

        private void UpdateChapterList()
        {
            var ni = NetworkInterface.NetworkInterfaceType;

            if (ni == NetworkInterfaceType.None)
            {
                // Navigato to page
                MessageBox.Show("You don't have any connection. Please try again.");
                return;
            }

            IsolatedStorageSettings issSetting = IsolatedStorageSettings.ApplicationSettings;

            if (issSetting.Contains("IsLoadedMangaDetail"))
            {
                if ((bool)issSetting["IsLoadedMangaDetail"] == true)
                {
                    // Get current chapter list
                    if (issSetting.Contains("MangaId"))
                    {
                        this.loadingBorder.Visibility = Visibility.Visible;
                        this.barLoading.IsIndeterminate = true;
                        MangaServiceClient mangaService = new MangaServiceClient();
                        mangaService.GetMangaStoryDetailAsync(App.KEYSITE, App.LINKMANGA);
                        mangaService.GetMangaStoryDetailCompleted += (sender, args) =>
                        {
                            App.ViewModel.GetChaptersByMangaId((int)issSetting["MangaId"]);
                            List<Chapter> oldChapterList = App.ViewModel.AllChapters.ToList<Chapter>();
                            int countOldList = oldChapterList.Count();
                            int countNewList = args.Result.Chapters.Count();

                            int different = countNewList - countOldList;
                            if (different > 0) // it's new chapter(s)
                            {
                                List<MangaChapter> newChapterList = args.Result.Chapters.ToList<MangaChapter>();

                                int startIndex = countNewList - different;
                                List<MangaChapter> newChaps = new List<MangaChapter>();

                                for (int count = 0; count < different; count++)
                                {
                                    newChaps.Add(newChapterList[count]);
                                }

                                App.ViewModel.InsertChaptersBaseOnMangaId((int)issSetting["MangaId"], newChaps);
                                App.ViewModel.GetChaptersByMangaId((int)issSetting["MangaId"]);
                                ListChapter.ItemsSource = App.ViewModel.AllChapters;
                                
                            }

                            this.loadingBorder.Visibility = Visibility.Collapsed;
                            this.barLoading.IsIndeterminate = false;
                            MessageBox.Show(String.Format("{0} chapters added.", different.ToString()));
                        };
                    }
                    //else
                    //{
                    //    // Navigato to page
                    //    MoveToPage();
                    //}
                }
                //else
                //{
                //    // Navigato to page
                //    MoveToPage();
                //}
            }
            //else
            //{
            //    // Navigato to page
            //    MoveToPage();
            //}

        }
    }
}